package prepared;

import utils.JDBCutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class AccountDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入转出金额");
        double money = sc.nextDouble();
    Account(money);
    }
    public static  void Account(Double money) {
        String sql = "update account set money = money- ? where id = ?";
        Connection con = null;
        PreparedStatement ps1 =null;
        PreparedStatement ps2 =null;

        try {
            con = JDBCutils.getConnection();
            //开启事务  false 手动提交
            con.setAutoCommit(false);
            ps1 = con.prepareStatement(sql);
            ps1.setDouble(1,money);
            ps1.setInt(2,1);
            int row = ps1.executeUpdate();
            if (row>0){
                System.out.println("转出成功");
            }else {
                System.out.println("转出失败");
            }
            //模拟银行断电
//            System.out.println(1/0);
            sql = "update account set money = money + ? where name = ?";
            ps2 = con.prepareStatement(sql);
            ps2.setDouble(1,money);
            ps2.setString(2,"lxl");
            int row1 = ps2.executeUpdate();
            if (row1>0){
                System.out.println("转入成功");
            }else{
                System.out.println("转出失败");
            }
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            //回滚事务
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        finally {
            try {
                ps1.close();
                ps2.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }
}
